package com.chance.web.app.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chance.common.constant.RedisConstant;
import com.chance.common.exception.LeaseException;
import com.chance.common.result.ResultCodeEnum;
import com.chance.common.utils.JwtUtil;
import com.chance.common.utils.VerifyCodeUtil;
import com.chance.model.entity.UserInfo;
import com.chance.model.enums.BaseStatus;
import com.chance.web.app.service.LoginService;
import com.chance.web.app.service.SmsService;
import com.chance.web.app.service.UserInfoService;
import com.chance.web.app.vo.user.LoginVo;
import com.chance.web.app.vo.user.UserInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SmsService smsService;


    @Autowired
    private UserInfoService userInfoService;


    @Override
    public void getSMSCode(String phone) {
        /*检查手机是否为空*/
        if (!StringUtils.hasText(phone)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        /*检查Redis中是否存在该手机号码的key*/
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + phone;
        Boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            /*若存在，则检查其存在的时间*/
            Long expire = redisTemplate.getExpire(key, TimeUnit.SECONDS);
            if(RedisConstant.APP_LOGIN_CODE_TTL_SEC - expire < RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC) {
                /*若存在时间不足一分钟，响应发送过于频繁*/
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }
        // 生成验证码发送并保存在redis中
        String verifyCode = VerifyCodeUtil.getVerifyCode(6);
        smsService.sendSms(phone, verifyCode);
        redisTemplate.opsForValue().set(key, verifyCode, RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);
    }

    @Override
    public String login(LoginVo loginVo) {
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();

        // 手机号和验证码是否为空
        if (!StringUtils.hasText(phone)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        if (!StringUtils.hasText(code)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }
        // 查询验证码是否存在
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + phone;
        Boolean hasKey = redisTemplate.hasKey(key);
        if (!hasKey) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }
        String redisCode = (String) redisTemplate.opsForValue().get(key);
        if (!redisCode.equals(code)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }

        UserInfo userInfo = userInfoService.getOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getPhone, phone));
        // 判断用户是否存在不存在则为用户创建
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setPhone(phone);
            userInfo.setNickname("用户-" + phone.substring(6));
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfoService.save(userInfo);
        }

        // 判断用户是否被禁用
        if (userInfo.getStatus().equals(BaseStatus.DISABLE)) {
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }

        // 返回token
        return JwtUtil.createToken(userInfo.getId(),phone);
    }

    @Override
    public UserInfoVo getUserInfoId(Long userId) {
        UserInfo userInfo = userInfoService.getById(userId);
        return new UserInfoVo(userInfo.getNickname(), userInfo.getAvatarUrl());
    }
}
